<template>
  <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px;;">
    <span>当前选择目录：</span>
    <el-select style="width: 60%;" v-model="select.dir" placeholder="选择目录" @change="changeDir">
      <el-option v-for="(v,i) in list.dir" :value="i" :label="v.desc+'：'+v.path" />
    </el-select>
    <el-button type="primary" style="margin-left: 10px;width: 20%;" @click="add">添加版本</el-button>
  </div>

  <el-table ref="versionTable" max-height="50vh" :data="list.version" border>
    <el-table-column prop="time" label="日期" width="200">
      <template #default="props">
        <span>{{ timeFormat(props.row.time) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="desc" label="描述"></el-table-column>
    <el-table-column width="200" label="操作">
      <template #default="props">
        <el-button type="primary" size="small" @click="expand(props.row)">查看</el-button>
        <el-button size="small" @click="editDesc(props.row)">修改</el-button>
        <el-button type="danger" size="small" @click="del(props.row)">删除</el-button>
      </template>
    </el-table-column>
    <el-table-column fixed type="expand">
      <template #default="props">
        <div style="margin:10px 20px;">
          <div v-for="v,k in files">{{ v.name }}</div>
        </div>
      </template>
    </el-table-column>
  </el-table>

  <hr style="margin:30px 0;height:1px;background-color: #ccc;border: none;" />

  <div>
    <p>文件列表变更对比（右侧新的对比左侧旧的所发生的变化）</p>
    <el-row>
      <el-col style="text-align: right;" :span="10">
        <span>旧的：</span>
        <el-select style="width: 80%;" v-model="select.old">
          <el-option value="now" label="当前" @click="input['old']=''" />
          <el-option v-for="v in list.version" :value="v.time" :label="timeFormat(v.time)+' | '+v.desc" @click="input['old']=v.desc" />
        </el-select>
      </el-col>
      <el-col class="middle" :span="4">
        <el-button type="primary" @click="compare">进行对比</el-button>
      </el-col>
      <el-col :span="10">
        <span>新的：</span>
        <el-select style="width: 80%;" v-model="select.new">
          <el-option value="now" label="当前" @click="input['new']=''" />
          <el-option v-for="v in list.version" :value="v.time" :label="timeFormat(v.time)+' | '+v.desc"  @click="input['new']=v.desc" />
        </el-select>
      </el-col>
    </el-row>
    <el-row style="margin-top:10px;">
      <el-col style="text-align: right;" :span="10">
        描述：<el-input v-model="input.old" class="elinput" />
      </el-col>
      <el-col class="middle" :span="4">
        <el-button type="primary" @click="doubleEditDesc">修改描述</el-button>
      </el-col>
      <el-col :span="10">
        描述：<el-input v-model="input.new" class="elinput" />
      </el-col>
    </el-row>
  </div>

  <hr style="margin:30px 0;height:1px;background-color: #ccc;border: none;" />

  <div>
    <p>
      变更详情
      <el-button style="margin-left:10px" type="primary" size="small" @click="exportCompare">导出</el-button>
    </p>

    <el-collapse v-model="collapse" style="margin-top: 20px;">
      <el-collapse-item title="树形结构" name="tree">
        <el-tree :data="list.tree" :default-expand-all="true">
          <template #default="{ node, data }">
            <div class="change-title">
              <span>{{ node.label }}</span>
              <span v-if="data.type=='add'" class="change-content" style="color: blue;"><el-icon><DocumentAdd /></el-icon>新增</span>
              <span v-if="data.type=='update'" class="change-content" style="color: green;"><el-icon><DocumentCopy /></el-icon>更新</span>
              <span v-if="data.type=='del'" class="change-content" style="color: red;"><el-icon><DocumentRemove /></el-icon>移除</span>
            </div>
          </template>
        </el-tree>
      </el-collapse-item>
      <el-collapse-item title="路径列表" name="path">
        <el-row>
          <el-col :span="8">
            <div class="change-title" style="color: red;"><el-icon><DocumentRemove /></el-icon>移除</div>
            <div v-for="v in list.compare.del">{{ v }}</div>
          </el-col>
          <el-col :span="8">
            <div class="change-title" style="color: green;"><el-icon><DocumentCopy /></el-icon>更新</div>
            <div v-for="v in list.compare.update">{{ v }}</div>
          </el-col>
          <el-col :span="8">
            <div class="change-title" style="color: blue;"><el-icon><DocumentAdd /></el-icon>新增</div>
            <div v-for="v in list.compare.add">{{ v }}</div>
          </el-col>
        </el-row>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>

<script lang="ts">
  import lh from '../utils/lh'
  import { ElMessage,ElMessageBox,ElLoading } from 'element-plus'

  export default {
    data() {
      return {
        collapse:"",//折叠面板
        files:{} as any,//文件列表
        list:{
          dir:[] as any,
          version:[] as any,
          tree:[],
          compare:{
            del:[],
            update:[],
            add:[]
          } as any,
        },
        select:{
          dir:0,//选择目录的索引
          new:'now',
          old:'now',
        } as any,
        input:{
          old:'',
          new:'',
        } as any,
      }
    },
    computed:{
      timeFormat(){
        return function(timestamp:number){
          var  date =  new  Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
          var  Y = date.getFullYear();
          var  M = date.getMonth()+1<10?'0'+(date.getMonth()+1):(date.getMonth()+1);
          var  D = date.getDate()<10?'0'+date.getDate():date.getDate();
          var  h = date.getHours()<10?'0'+date.getHours():date.getHours();
          var  m = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes();
          var  s = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
          return  Y+'-'+M+'-'+D+' '+h+':'+m+':'+s;
        }
      }
    },
    created(){
      lh.post('/dir/list').then(o=>{
        this.list.dir=o
        //切换默认目录
        if(o.length)this.changeDir(0)//默认选第一个
        for (let i = 0; i < o.length; i++) {
          if(o[i].default){
            this.changeDir(i)
            break
          }
        }
      }).catch(e=>{
        console.log(e)
        ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
      })
    },
    methods:{
      //导出对比
      exportCompare(){
        if(!this.list.compare.add.length&&!this.list.compare.del.length&&!this.list.compare.update.length){
          ElMessage({type:'warning',message: '没有变更内容'})
          return
        }
        let str=JSON.stringify({tree:this.list.tree,list:this.list.compare})
        let blob = new Blob([str])
        let link = document.createElement("a")
        link.href = URL.createObjectURL(blob)
        link.download = 'compare.json'
        link.click()
      },
      //版本对比两边一起修改描述
      doubleEditDesc(){
        for(let v of ['old','new']){
          if(this.select[v]=='now')continue
          let param={
            time:this.select[v],
            desc:this.input[v]
          }
          this.editDesc(param,true)
        }
      },
      //改变版本对比的描述
      changeDesc(pos:string,desc:string){
        this.input[pos]=desc
      },
      //变更对比
      compare(){
        if(this.select.old==this.select.new){
          ElMessage({type:'warning',message: '两者一样，无需对比'})
          return
        }

        const loading = ElLoading.service({
          lock: true,
          text: 'Loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })
        lh.post('/version/compare',{
          old:this.select.old,
          new:this.select.new
        }).then(o=>{
          o.tree[0].label=this.list.dir[this.select.dir].path
          this.list.tree=o.tree
          this.list.compare=o.compare
          this.collapse="tree"
          ElMessage({type:'success',message: '对比完成'})
        }).catch(e=>{
          console.log(e)
          ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
        }).finally(()=>{
          loading.close()
        })
      },
      //展开文件列表
      expand(row:any){
        (this.$refs.versionTable as any).toggleRowExpansion(row)

        //获取row的文件列表
        lh.post('/version/list/get',{
          time:row.time
        }).then(o=>{
          this.files=o
        }).catch(e=>{
          console.log(e)
          ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
        })
      },
      //切换目录
      changeDir(i:number){
        lh.post('/version/list',{id:this.list.dir[i].id}).then(o=>{
          this.select.dir=i
          this.list.version=o
        }).catch(e=>{
          console.log(e)
          ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
        })
      },
      //修改版本描述
      editDesc(row:any,quick=false){
        let fn=(value:string)=>{
          lh.post('/version/desc/edit',{
            time:row.time,
            desc:value
          }).then(o=>{
            this.list.version=o
            ElMessage({type:'success',message: '修改描述成功',})
          }).catch(e=>{
            console.log(e)
            ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
          })
        }
        
        //两边快速修改
        if(quick){
          fn(row.desc)
          return
        }

        ElMessageBox.prompt('修改 '+this.timeFormat(row.time)+' '+row.desc+' 的描述','提示',{
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          inputValue:row.desc,
        }).then(({value})=>{
          fn(value)
        }).catch(()=>{})
      },
      //删除版本
      del(row:any){
        ElMessageBox.confirm('是否确定删除版本：'+this.timeFormat(row.time)+' ('+row.desc+')', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          lh.post('/version/del',{time:row.time}).then(o=>{
            this.list.version=o
            ElMessage({type:'success',message: '删除成功',})
          }).catch(e=>{
            console.log(e)
            ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
          })
        }).catch(()=>{})
      },
      //添加版本
      add(){
        ElMessageBox.prompt('将会记录 '+this.list.dir[this.select.dir].desc+'：'+this.list.dir[this.select.dir].path+' 的当前文件列表，请填写版本描述(如：百度网盘，阿里云盘)','提示',{
          confirmButtonText: '确认',
          cancelButtonText: '取消',
        }).then(({value})=>{
          const loading = ElLoading.service({
            lock: true,
            text: 'Loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          
          lh.post('/version/add',{desc:value}).then(o=>{
            this.list.version=o
            ElMessage({type:'success',message: '添加成功',})
          }).catch(e=>{
            console.log(e)
            ElMessageBox.alert(e, '错误', {confirmButtonText: '确认'})
          }).finally(()=>{
            loading.close()
          })
        }).catch(()=>{})
      }
    }
  }
</script>

<style scoped>
  .change-title{
    display: flex;
    align-items: center;
  }
  .change-title i{
    margin-right: 5px;
  }
  .change-content{
    margin-left:20px;
  }
  .middle{
    text-align: center;
  }
  .elinput{
    width: 80%;
  }
</style>